package com.infra.micro.quartz.domain.core;

import com.infra.micro.quartz.domain.entity.QuartzJobPO;
import com.infra.micro.quartz.domain.service.QuartzJobService;
import com.infra.micro.quartz.model.vo.QuartzJobVO;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.CronTrigger;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@MapperScan(basePackages = {"com.infra.micro.quartz.domain.mapper"})
public class SpringRunner implements ApplicationRunner {
    @Resource
    private QuartzJobService sysQuartzJobService;

    @Resource
    private QuartzJobManage quartzJobManage;

    /**
     * 项目启动时重新激活启用的定时任务
     *
     * @param args /
     */
    @Override
    public void run(ApplicationArguments args) {
        System.out.println("--------------------注入定时任务---------------------");
        List<QuartzJobPO> quartzJobs = sysQuartzJobService.queryList(false);
        quartzJobs.forEach(item -> {
            QuartzJobVO quartzJobVO = new QuartzJobVO();
            BeanUtils.copyProperties(item, quartzJobVO);
            CronTrigger cronTrigger = quartzJobManage.getCronTrigger(quartzJobVO.getJobId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                quartzJobManage.addJob(quartzJobVO);
            } else {
                quartzJobManage.updateJobCron(quartzJobVO);
            }
        });
        System.out.println("-------------------定时任务注入完成--------------------");
    }
}
